package com.kuang.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.kuang.pojo.User;
import com.kuang.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import static com.kuang.utils.JsonUtils.getJson;

//@Controller
@RestController //标记类下面的所有方法只会返回字符串
public class UserController {

    //解决乱码使用produces
    //@RequestMapping(value = "/j1", produces = "application/json;charset=utf-8") //乱码解决方式一
    @RequestMapping("/j1") //解决方式二，配置springXML配置文件
    //@ResponseBody //不会走视图解析器，会直接返回一个字符串
    public String test1(Model model) throws JsonProcessingException {
        //jackson
        ObjectMapper mapper = new ObjectMapper();

        List<User> users = new ArrayList<User>();

        //创建一个对象
        User user1 = new User("小黑", 12, "女");
        User user2 = new User("小兰", 12, "女");
        User user3 = new User("小蓝", 12, "女");

        users.add(user1);
        users.add(user2);
        users.add(user3);

//        return mapper.writeValueAsString(user1);
        return mapper.writeValueAsString(users);
    }

    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException, Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        //方式二，不适用默认的时间戳
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //设置自己时间戳
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));


        Date date = new Date();

        //方式一、自定义日期的格式
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String  format = simpleDateFormat.format(date);

//        return objectMapper.writeValueAsString(format);//第一种方式
        return objectMapper.writeValueAsString(date);//第二种方式
    }

    @RequestMapping("j4")
    public String json4() throws Exception {
        return JsonUtils.getJson(new Date());
    }

    //fastJson
    @RequestMapping("j5")
    public String fastJson(){
        List<User> users = new ArrayList<User>();

        //创建一个对象
        User user1 = new User("小黑", 12, "女");
        User user2 = new User("小兰", 12, "女");
        User user3 = new User("小蓝", 12, "女");

        users.add(user1);
        users.add(user2);
        users.add(user3);

        return JSON.toJSONString(users);
    }

}
